//
//  YTStashViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/7/1.
//

#import "YTStashViewController.h"
#import "YTStashLeftTableViewCell.h"
#import "YTStashRightTableViewCell.h"
#import "YTStashLeftModel.h"
#import "YTStashDetailsViewController.h"
#import "YTStashSearchViewController.h"
#import "YTStashPutAndOutShowView.h"
#import "YTStashRecordsDetailsViewController.h"


#import "YTStashAllListViewController.h"

@interface YTStashViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView * leftTableview;
@property (nonatomic ,strong) NSMutableArray<YTStashLeftModel *> * leftModelArray;
@property (nonatomic ,strong) NSMutableArray<YTStashListModel *> * modelArray;
@property (nonatomic ,strong) UIView * topview;

@end

@implementation YTStashViewController

- (NSMutableArray<YTStashLeftModel *> *)leftModelArray{
    if(!_leftModelArray){
        _leftModelArray = [NSMutableArray array];
    }
    return _leftModelArray;
}
- (NSMutableArray<YTStashListModel *> *)modelArray{
    if(!_modelArray){
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupview];
}
- (void)setupview{
    UIView * topview = [UIView new];
    [self.view addSubview:topview];
    self.topview = topview;
    topview.backgroundColor = KcolorHex(@"#0967FF");
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.left.offset(0);
        make.height.offset(KTop + kwt(56));
    }];
    
    UIView * ssview = [UIView new];
    ssview.backgroundColor = UIColor.whiteColor;
    [topview addSubview:ssview];
    [ssview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(kwt(320));
        make.height.offset(kwt(40));
        make.centerY.offset(KTop/2);
        make.centerX.offset(0);
    }];
    MJWeakSelf
    ssview.addClickBlock(^{
        YTStashSearchViewController * vc = [YTStashSearchViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    });
    [DTKTool YJ:kwt(5) andView:ssview];
    
    UIImageView * ssimg = kimageView(@"program_search");
    [ssview addSubview:ssimg];
    [ssimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(15));
        make.width.height.offset(kwt(16));
        make.centerY.offset(0);
    }];
    
    UILabel * sslab = [DTKTool labelWithText:@"请搜索品种" andFont:kFont(16) andTextColor:KcolorHex(@"#89908D")];
    [ssview addSubview:sslab];
    [sslab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ssimg.mas_right).offset(kwt(10));
        make.centerY.offset(0);
    }];
    
    [self.view addSubview:self.leftTableview];
    [self.view addSubview:self.tableview];
    self.tableview.backgroundColor = UIColor.whiteColor;
    [self.leftTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.offset(0);
        make.width.offset(kwt(90));
        make.top.equalTo(topview.mas_bottom);
    }];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.offset(0);
        make.top.equalTo(topview.mas_bottom);
        make.left.equalTo(self.leftTableview.mas_right);
    }];
    [self addFooterView:^{
        [weakSelf addMoreData];
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self kindOption];

}

-(void)addMoreData{
    self.pageNo += 1;
    [self loadNewData];
}

- (void)refreshingData{
    self.pageNo = 1;
    [self.modelArray removeAllObjects];
    [self loadNewData];
}

- (void)kindOption{
    [self.view showBusyHUD];
    // 仓库物品品类下拉列表
    [SCNetManger warehousekindOptionWithDict:[NSMutableDictionary dictionary] andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        if(model.code == 200){
            NSArray * array = [NSArray yy_modelArrayWithClass:YTStashLeftModel.class json:model.result];
            [self.tableview mas_remakeConstraints:^(MASConstraintMaker *make) {
                if(array.count > 0){
                    make.left.equalTo(self.leftTableview.mas_right);
                } else {
                    make.left.equalTo(self.leftTableview.mas_left);
                }
                make.right.bottom.offset(0);
                make.top.equalTo(self.topview.mas_bottom);
            }];
            if(self.leftModelArray.firstObject.isSeled || self.leftModelArray.count < 1){
                self.leftModelArray = [NSMutableArray arrayWithArray:array];
                self.leftModelArray.firstObject.isSeled = YES;
            } else {
                for (YTStashLeftModel * m in self.leftModelArray) {
                    for (YTStashLeftModel * newM in array) {
                        if(m.isSeled && [newM.ID isEqualToString:m.ID]){
                            newM.isSeled = YES;
                        }
                    }
                }
                self.leftModelArray = [NSMutableArray arrayWithArray:array];
            }
          
            [self.leftTableview reloadData];
            [self.tableview reloadData];
            [self refreshingData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
- (void)loadNewData{
    if(self.leftModelArray.count < 1){
        [self.modelArray removeAllObjects];
        [self.tableview reloadData];
        return;
    }

    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    for (YTStashLeftModel * model in self.leftModelArray) {
        if(model.isSeled){
            [dict setObject:model.SeledID forKey:@"categoryId"];
        }
    }
    
    [dict setObject:@(self.pageNo) forKey:@"pageNo"];
    [dict setObject:@(self.pageSize) forKey:@"pageSize"];
    
    // 仓库物品品类下拉列表
    [SCNetManger warehouseManageListWithDict:dict andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        if(model.code == 200){
            NSArray * array = [NSArray yy_modelArrayWithClass:YTStashListModel.class json:model.result[@"records"]];
            if(array.count == 0 && self.modelArray.count > 0){
                [self.tableview.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.tableview.mj_footer endRefreshing];
            }
            [self.modelArray addObjectsFromArray:array];
            [self.tableview.mj_header endRefreshing];
            [self.tableview reloadData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}


- (UITableView *)leftTableview{
    if(!_leftTableview){
        _leftTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kwt(120), SCREEN_WIDTH, SCREEN_HEIGHT - kwt(120)) style:UITableViewStyleGrouped];
        _leftTableview.delegate = self;
        _leftTableview.dataSource = self;
        _leftTableview.backgroundColor = KcolorHex(@"#F0F0F0");
        if (@available(iOS 11.0, *)) {
            _leftTableview.estimatedRowHeight = 0;
            _leftTableview.estimatedSectionHeaderHeight = 0;
            _leftTableview.estimatedSectionFooterHeight = 0;
            _leftTableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _leftTableview.sectionHeaderTopPadding = 0;
            _leftTableview.fillerRowHeight = 0;
        }
        _leftTableview.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _leftTableview.sectionHeaderHeight = 0.01;
        _leftTableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _leftTableview.sectionFooterHeight = 0.01;
        _leftTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _leftTableview.backgroundColor = UIColor.clearColor;
    }
    return _leftTableview;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if(tableView == self.tableview){
        UIView * view = [UIView new];
        UIScrollView * scrollview = [UIScrollView new];
        [view addSubview:scrollview];
        [scrollview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.bottom.offset(0);
        }];
        CGFloat X = kwt(14);
        MJWeakSelf
        for (YTStashLeftModel * leftmodel in self.leftModelArray) {
            if(leftmodel.isSeled){
                for (YTStashLeftModel * model in leftmodel.AllchildList) {
                    UILabel * btnview = [DTKTool labelWithText:model.name andFont:kFont(15) andTextColor:KcolorHex(@"#222222")];
                    btnview.textAlignment = NSTextAlignmentCenter;
                    if(model.isSeled){
                        btnview.textColor = UIColor.whiteColor;
                        btnview.backgroundColor = [UIColor gradientColorWithSize:CGSizeMake(model.nameW, 1) direction:GradientColorDirectionLevel startColor:KcolorHex(@"#427FFF") endColor:KcolorHex(@"#3D5FFF")];
                    } else {
                        btnview.backgroundColor = KcolorHex(@"#E9E9E9");
                        btnview.addClickBlock(^{
                            for (YTStashLeftModel * model in leftmodel.AllchildList) {
                                model.isSeled = NO;
                            }
                            model.isSeled = YES;
                            [weakSelf refreshingData];
                        });
                    }
                    [scrollview addSubview:btnview];
                    btnview.frame = CGRectMake(X, kwt(10), model.nameW, kwt(30));
                    [DTKTool YJ:kwt(15) andView:btnview];
                    X += kwt(12) + model.nameW;
                }
                scrollview.contentSize = CGSizeMake(X, 0);
                return view;
            }
        }
        return  view;
    }
    return [UIView new];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(tableView == self.tableview){
        for (YTStashLeftModel * leftmodel in self.leftModelArray) {
            if(leftmodel.isSeled){
                if(leftmodel.childList.count > 0){
                    return kwt(50);
                }
            }
        }
        return kwt(5);
    }
    return kwt(5);
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(tableView == self.tableview){
        return self.modelArray.count;
    }
    return self.leftModelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView == self.tableview){
        if(self.modelArray.count > indexPath.row){
            return self.modelArray[indexPath.row].CellH;
        }
    }
    return kwt(68);
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if(tableView == self.tableview){
        YTStashRightTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"YTStashRightTableViewCell"];
        if (cell == nil) {
            cell = [[YTStashRightTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YTStashRightTableViewCell"];
        }
        if(self.modelArray.count > indexPath.row){
            cell.model = self.modelArray[indexPath.row];
        }
        MJWeakSelf
        cell.crkBlock = ^(YTStashListModel * _Nonnull model) {
            NSString * json = [model yy_modelToJSONString];
            YTStashListModel * listmodel = [YTStashListModel yy_modelWithJSON:json];
            [YTStashPutAndOutShowView showviewWithModel:listmodel andBlock:^{
                [weakSelf refreshingData];
            }];
        };
        cell.ckBlock = ^(YTStashListModel * _Nonnull model) {
            NSString * json = [model yy_modelToJSONString];
            YTStashListModel * listmodel = [YTStashListModel yy_modelWithJSON:json];
            [YTStashOutShowView showviewWithModel:listmodel andBlock:^{
                [weakSelf refreshingData];
            }];
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    }
    
    YTStashLeftTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"YTStashLeftTableViewCell"];
    if (cell == nil) {
        cell = [[YTStashLeftTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YTStashLeftTableViewCell"];
    }
    cell.model = self.leftModelArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == self.tableview){
        YTStashDetailsViewController * vc = [YTStashDetailsViewController new];
        vc.ID = self.modelArray[indexPath.row].ID;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        if(self.leftModelArray[indexPath.row].isSeled == NO){
            for (YTStashLeftModel * model in self.leftModelArray) {
                model.isSeled = NO;
            }
            self.leftModelArray[indexPath.row].isSeled = YES;
            [self.leftTableview reloadData];
            [self refreshingData];
        }
    }
}


@end
